package com.lyb.ui.authentication.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.gxb.crawler.sdk.FinishCallBackListener;
import com.gxb.crawler.sdk.GxbCrawlerSdk;
import com.gxb.crawler.sdk.GxbParams;
import com.gxb.crawler.sdk.IBackListener;
import com.just.agentwebX5.AgentWebX5;
import com.lyb.R;
import com.lyb.app.App;
import com.lyb.base.BaseActivity;
import com.lyb.config.Constant;
import com.lyb.dialog.AlertFragmentDialog;
import com.lyb.events.ChangeTabMainEvent;
import com.lyb.ui.authentication.contract.GxbContract;
import com.lyb.ui.authentication.presenter.GxbAuthPresenter;
import com.lyb.ui.main.FragmentFactory;
import com.lyb.ui.main.MainActivity;
import com.lyb.ui.main.WebViewActivity;
import com.lyb.util.SpUtil;
import com.lyb.util.ToastUtil;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.TreeMap;

import butterknife.BindView;

/**
 * Created by ls
 * 2018/11/23
 * note:
 */
public class GxbAuthActivity extends BaseActivity<GxbAuthPresenter> implements
        GxbContract.View {

    private static final String TAG = "retrofit_返回数据";
    private LinearLayout ll;
    private String AUTH_URL = "https://prod.gxb.io/v2/auth?returnUrl=https://www.baidu.com/?success=0&remark=数据推送失败&subItem=taobao&token=";
    private AgentWebX5 agentWeb;

    @BindView(R.id.progressbar)
    ProgressBar mProgressBar;

    @Override
    public int getLayoutId() {
        return R.layout.activity_gxb_auth;
    }

    @Override
    public void initPresenter() {
        mPresenter.init(this);
    }

    @Override
    public void loadData() {
        mTitle.setTitle(R.string.perfect_taobao);
        initQBSdk();
        ll = (LinearLayout) findViewById(R.id.ll);
        mPresenter.getToken();
//        goWebX5("0245400917000zJKS3XpAIfYZkNpS5vA");
    }


    private void initQBSdk() {
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                Log.e("2121212", arg0 + "");
            }

            @Override
            public void onCoreInitFinished() {

            }
        };
        QbSdk.initX5Environment(this, cb);
    }

    @Override
    public void getTokenSuccess(String token) {
        goWebX5(token);
    }

    @Override
    public void showLoading(String content) {
        App.loadingContent(this, content);
    }

    @Override
    public void stopLoading() {
        App.hideLoading();
    }

    @Override
    public void showErrorMsg(String msg, String type) {
        ToastUtil.showToast(msg);
    }


    private void goWebX5(String token) {
        agentWeb = AgentWebX5.with(this)
                .setAgentWebParent(ll, new LinearLayout.LayoutParams(-1, -1))
                .closeProgressBar()
                .setWebViewClient(new MyClient())
                .setWebChromeClient(new MyWebChromeClient())
                .createAgentWeb()
                .ready()
                .go(AUTH_URL + token);
    }

    private class MyClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.e(TAG, "onPageStarted: " + url);
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e(TAG, "onPageFinished: " + url);
            mProgressBar.setVisibility(View.GONE);
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e(TAG, "shouldOverrideUrlLoading: " + url);
            if (url.contains("www.baidu.com")) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.show("授权成功");
                        try {
                            Intent intent = new Intent(GxbAuthActivity.this, PerfectInformationActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                return true;
            }
            if (!TextUtils.isEmpty(url)) {
                //设置Schemes白名单
//                String[] whiteList = {"taobao://", "alipayqr://", "alipays://", "wechat://", "weixin://", "mqq://", "mqqwpa://", "openApp.jdMobile://", "openapp.jdmobile://"};
                //判断url如果是在Schemes的白名单里，就启动对于的app，如果不是直接加载url
                if (url.startsWith("alipayqr://") || url.startsWith("weixin://") || url.startsWith("taobao://")) {
                    try {
                        Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        intent.addCategory(Intent.CATEGORY_BROWSABLE);
                        startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                //如果是native 则需要加个过滤
                Uri uri = Uri.parse(url);
                Log.e(TAG, "shouldOverrideUrlLoading: " + uri);
                if (uri.getScheme().equals("native")) {
                    if (uri.getAuthority().equals("openUrl")) {
                        String url1 = uri.getQueryParameter("commandUrl");
                        GxbParams params = new GxbParams.Builder()
                                .setKeyBackListener(new IBackListener() {
                                    @Override
                                    public void onBack() {
//                                        Toast.makeText(GxbAuthActivity.this, "按返回了", Toast.LENGTH_SHORT).show();
                                    }
                                })
                                .build();

                        GxbCrawlerSdk.INSTANCE.init(params);
                        GxbCrawlerSdk.INSTANCE.auth(GxbAuthActivity.this, url1, new FinishCallBackListener() {
                            @Override
                            public void finish(boolean success) {
                                String a = "授权";
                                if (success) {
                                    a = "授权成功";
                                } else {
                                    a = "授权失败";
                                }
                                Toast.makeText(GxbAuthActivity.this, a, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    @Override
    public void onBackPressed() {
        new AlertFragmentDialog.Builder(this)
                .setContent("返回操作将中断淘宝认证，\n确认要退出吗？")
                .setLeftBtnText("取消认证")
                .setRightBtnText("继续认证")
                .setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                    @Override
                    public void dialogLeftBtnClick() {
                        finish();
                    }
                }).build();
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView webView, int i) {
            mProgressBar.setProgress(i);
        }
    }
}
